<template>
  <div class='settlement'>
    <van-cell-group class="cards" :border="false" inset @click="jump">
      <van-cell class="address" :title="concatAddress" :border="false" is-link center>
        <template #label>
          <span>{{address?.name}}</span>
          <span class="tel">{{address?.phone}}</span>
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell-group class="cards" :border="false" inset>

      <van-card class="product" :price="info.sale_price" :desc="info.content" :title="info.service_name" :thumb="`${resourceURL}${info.top_pic}`">
        <template #num>
          <van-stepper v-model="quantity" integer />
        </template>
      </van-card>

    </van-cell-group>
    <van-cell-group :border="false" inset class="allPrice">
      <van-cell title="总价" :border="false" center :value="(info.sale_price*quantity).toFixed(2)">

      </van-cell>

    </van-cell-group>
    <van-cell-group :border="false" inset @click="show=true">
      <van-cell title="请上门时间：" :border="false" :is-link="time?false:true" center :value="time">

      </van-cell>

    </van-cell-group>
    <van-goods-action>

      <van-goods-action-button type="danger" text="立即预约" @click="onPayment" :disabled="(!this.time||!this.address.address_id)" />
    </van-goods-action>
    <van-popup v-model="show" round position="bottom">

      <van-datetime-picker v-model="currentDate" type="datehour" title="选择年月日小时" :min-date="minDate" :max-date="maxDate" :filter="filter" @cancel="show=false" @confirm="confirmTime" :formatter="formatter" />
    </van-popup>
  </div>
</template>

<script>
import { Toast } from 'vant';

export default {

  data () {
    return {
      receive_id: null,
      address: {},
      show: false,
      currentDate: '',
      list: [],
      price: {},
      coupon_amount: '',
      minDate: '',
      maxDate: '',
      info: JSON.parse(localStorage.getItem('HousekeepingDetail')) || {},
      time: '',
      quantity: 1,
    }
  },
  created () {
    this.getDefaultaddress()

    if (this.$route.query.item) {
      this.address = JSON.parse(this.$route.query.item)

    }

    this.gettime()
  },
  computed: {
    // 拼接完整地址
    concatAddress () {
      if (this.address.province_name) {
        return this.address?.province_name + this.address?.city_name + this.address?.area_name + this.address?.detail
      } else {
        return ''
      }

    },

  },
  methods: {
    //确认时间
    confirmTime (value) {
      this.time = this.$moment(value).format('YYYY-MM-DD HH:mm:ss')

      this.show = false
    },
    formatter (type, val) {
      if (type === 'year') {
        return val + '年';
      }
      if (type === 'month') {
        return val + '月';
      }
      if (type === 'day') {
        return val + '日';
      }
      if (type === 'hour') {
        return val + '时';
      }
      return val;
    },
    //获取预约时间
    gettime () {

      let day1 = this.$moment().add(1, 'days').format('YYYY-MM-DD');
      day1 = this.$moment(`${day1} 00:00:00`).valueOf();
      let day2 = this.$moment().add(7, 'days').format('YYYY-MM-DD');
      day2 = this.$moment(`${day2} 22:00:00`).valueOf();


      this.maxDate = new Date(day2)

      this.minDate = new Date(day1)


    },
    //限定时间为8点到6点
    filter (type, options) {
      if (type === 'hour') {
        return options.filter((option) => option > 7 && option < 22);
      }
      return options;
    },
    // 获取收货地址
    getDefaultaddress () {
      this.$axios.get(this.$api.getdefaultaddress).then(res => {


        if (this.$route.query.item) {
          Toast.clear();
        } else {
          if (res.data.code == 1) {
            this.address = res.data.data
          }
        }



      })
    },
    // 下单
    onPayment () {
      if (this.address) {

        this.$axios.post(this.$api.serviceDownorder, {
          make_time: this.time,
          service_id: this.info.service_id,
          address_id: this.address.address_id,
          quantity: this.quantity,

        }).then(res => {
          if (res.data.code == 1) {

            this.StartWeiXinPay(res.data.data)
            console.log(res.data.data);
          } else {
            Toast.fail(res.data.msg)
          }
        })
      } else {
        Toast.fail('暂无收货地址')
      }
    },
    // 调取微信支付
    StartWeiXinPay (pay_params) {
      if (typeof window.WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(pay_params), false)
          alert(1);
        } else if (document.attachEvent) {
          alert(2);
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(pay_params))
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(pay_params))
        }
      } else {
        this.onBridgeReady(pay_params)
      }
    },
    onBridgeReady (pay_params) {
      var that = this
      window.WeixinJSBridge.invoke('getBrandWCPayRequest', {
        'appId': pay_params.appId, // 公众号名称，由商户传入
        'timeStamp': pay_params.timeStamp, // 时间戳，自1970年以来的秒数
        'nonceStr': pay_params.nonceStr, // 随机串
        'package': pay_params.package, //统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
        'signType': pay_params.signType, // 微信签名方式：
        'paySign': pay_params.paySign // 微信签名
      },
        function (res) {

          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            setTimeout(() => {

              that.$router.replace({ name: 'bookingSucess', query: { send_id: pay_params.send_id } })


            }, 500);
          } else {
            Toast.fail('支付失败')
          }
        }
      )
    },
    //跳转至选择地址页
    jump () {
      this.$router.push({
        name: 'chooseAddress',
        query: {
          name: 'payment'
        }
      })
    }
  },
}
</script>

<style scoped lang='less'>
.settlement {
  padding-top: 16px;
  .cards {
    margin-bottom: 12px;
    /deep/.van-icon__image {
      width: 100%;
      height: 100%;
    }
    .address {
      /deep/.van-cell__title {
        font-size: 14px;
        font-weight: bold;
      }
      /deep/.van-cell__label {
        font-size: 14px;
        font-weight: 500;
      }
    }
    .shopurl {
      .van-cell__left-icon {
        display: flex;
        align-items: center;
        width: 20px;
        height: 22px;
        margin-right: 8px;
      }
    }
    .product {
      margin-top: 0;
      background-color: #fff;
      /deep/.van-card__title {
        font-size: 14px;
      }
      /deep/ .van-card__price {
        font-size: 14px;
      }
    }
    .price_detail {
      font-weight: bold;
    }
    .coupon {
      .van-cell__left-icon {
        display: flex;
        align-items: center;
        width: 22px;
        height: 22px;
        margin-right: 8px;
      }
      .not_coupon {
        font-size: 12px;
        color: #bbb9b7;
      }
      .is_coupon {
        font-size: 12px;
        color: #fb2b2c;
      }
    }
  }
  .tel {
    margin-left: 16px;
  }
  .price_total {
    /deep/.van-cell__value {
      color: #06021a;
      font-size: 14px;
      font-weight: bold;
    }
  }
  .allPrice {
    margin-bottom: 12px;
  }
  .submit {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    padding: 5px 16px;
    border-radius: 16px 16px 0 0;
    background-color: #fff;
    box-sizing: border-box;
    .price_info {
      display: flex;
      flex-flow: column wrap;
      align-items: flex-end;
      margin-right: 16px;
      .settlement_total {
        font-size: 12px;
        .pay_amount span {
          color: #fb2b2c;
          font-size: 18px;
          font-weight: bold;
        }
      }
      .coupon_amount {
        color: #fb2b2c;
        font-size: 12px;
      }
    }
    .van-button {
      min-width: 102px;
    }
  }
  .num_total {
    color: #bbb9b7;
    font-size: 12px;
    margin-left: 14px;
    margin-right: 8px;
  }
}
button {
  background: linear-gradient(to right, #ff7733, #ff7733);
}
</style>
